package com.yanggeng.demo.beginnerguidedemo.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理字符串的工具类
 *
 * @author allen@tronsis.com
 */
public class StringUtil {
    private final static String REGXP_FOR_HTML = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签

    /**
     * 判断一个字符串为null或长度为0或是空格符
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {

        return (str == null || str.trim().length() == 0);
    }

    /**
     * 判断一个字符串是否为null或长度为0
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {

        return (str == null || str.trim().length() == 0);
    }

    /**
     * 比较两个字符串
     *
     * @param actual
     * @param expected
     * @return 一样则返回true, 否则返回false
     */
    public static boolean isEquals(String actual, String expected) {

        return actual == expected || (actual == null ? expected == null : actual.equals(expected));
    }

    /**
     * 把为null的String对象转换为空字符串
     *
     * @param str
     * @return
     */
    public static String nullStrToEmpty(String str) {

        return (str == null ? "" : str);
    }

    /**
     * 判断是否是手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean isMobileNo(String mobile) {
        if (StringUtil.isBlank(mobile)) {
            return false;
        }
        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,0-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * new
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        if (isBlank(mobile)) {
            return false;
        }
        return Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$").matcher(mobile).matches();
    }

    /**
     * 判断是否是邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (StringUtil.isBlank(email)) {
            return false;
        }
        Pattern p = Pattern.compile("^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$");
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 判断是否是数字
     *
     * @param number
     * @return
     */
    public static boolean isNumber(String number) {
        try {
            Long.parseLong(number);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 基本功能：过滤所有以"<"开头以">"结尾的标签
     *
     * @param str
     * @return String
     */
    public static String filterHtml(String str) {
        Pattern pattern = Pattern.compile(REGXP_FOR_HTML);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result1 = matcher.find();
        while (result1) {
            matcher.appendReplacement(sb, "");
            result1 = matcher.find();
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * MD5加密
     *
     * @param plainText 需要加密的字符串
     * @return 加密后字符串
     */
    public static String md5(String plainText) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString().toLowerCase();// 32位的加密（转成小写）

            buf.toString().substring(8, 24);// 16位的加密

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断密码是否含有大小写字母及数组
     */
    public static boolean isWellFormedPwd(String password) {
        if (password.length() >= 8 && password.length() <= 20) {
            if (password.matches("[a-zA-Z0-9_@]+")) {
                Pattern p1 = Pattern.compile("[a-z]+");
                Pattern p2 = Pattern.compile("[A-Z]+");
                Pattern p3 = Pattern.compile("[0-9]+");
                Matcher m = p1.matcher(password);
                if (!m.find()) {
                    return false;
                } else {
                    m.reset().usePattern(p2);
                    if (!m.find()) {
                        return false;
                    } else {
                        m.reset().usePattern(p3);
                        if (!m.find()) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * SHA256加密
     *
     * @param src 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String sha256(String src) {
        MessageDigest messageDigest = null;
        String strDes = null;
        byte[] bytes = src.getBytes();
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(bytes);
            strDes = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return strDes;
    }

    /**
     * byte数组转换为16进制字符串
     *
     * @param bytes 数据源
     * @return 16进制字符串
     */
    public static String byte2Hex(byte[] bytes) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bytes.length; i++) {
            tmp = (Integer.toHexString(bytes[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    //  十六进制的字符串转换成byte数组
    public static byte[] HexCommandtoByte(byte[] data) {
        if (data == null) {
            return null;
        }
        int nLength = data.length;
        String strTemString = new String(data, 0, nLength);
        String[] strings = strTemString.split(" ");
        nLength = strings.length;
        data = new byte[nLength];
        for (int i = 0; i < nLength; i++) {
            if (strings[i].length() != 2) {
                data[i] = 00;
                continue;
            }
            try {
                data[i] = (byte) Integer.parseInt(strings[i], 16);
            } catch (Exception e) {
                data[i] = 00;
                continue;
            }
        }
        return data;
    }

    /**
     * 16进制字符串转换成byte数组
     * @param str 16进制字符串
     * @return
     */
    public static byte[] toBytes(String str) {
        if(TextUtils.isEmpty(str)) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    public static String checkHttp(String url){
        String http="http:";
        if (!isBlank(url) && !url.startsWith("http")){
            return http + url;
        }
        return url;
    }

    public static String reverse(String str){
        return new StringBuilder(str).reverse().toString();
    }


    /**
     * 逗号隔开的数组
     * @param mList
     * @return
     */
    public static String arrayList(List<String> mList){
        String str = mList.toString();
        int len = str.length() - 1;
        return str.substring(1, len).replace(" ", "");//"keyids":”1,2,3”
    }

}